<?php

namespace app\admin\controller;

use think\facade\Db;
use app\admin\model\Adsense as adsenseModel;
use think\facade\Request;
use think\facade\View;

class Adsense extends Common
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 广告位列表
     * @author admin
     * @date 2019-08-08
     */
    public function index()
    {
        if (Request::isPost()) {
            $list =  Db::name('ad_postion')->select()->toArray();
            return ['code' => 0, 'msg' => '获取成功！', 'data' => $list];
        }
        return View::fetch();
    }


    /**
     * 添加广告位
     * @author admin
     * @date 2019-08-08
     */

    public function add()
    {
        try {
            if (Request::isPost()) {
                $data = input('post.');
                $data['create_time'] = time();
                adsenseModel::create($data);
                return ['code' => 0, 'msg' => '添加成功！'];
            } else {
                return View::fetch('edit');
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 编缉广告位
     * @author admin
     * @date 2019-08-08
     */
    public function edit()
    {
        try {
            if (request()->isPost()) {
                $data = input('post.');
                $where['ad_postion_id'] = $data['ad_postion_id'];
                Db::name('ad_postion')->where($where)->update($data);
                return ['code' => 0, 'msg' => '修改成功！'];
            } else {
                $id = input('get.id');
                if (!$id) {
                    return ['code' => 2000, 'msg' => '非法请求！'];
                }
                $info = Db::name('ad_postion')->where('ad_postion_id',$id)->find();
                $this->assign('info', $info);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }



    /**
     * 删除广告位
     * @author admin
     * @date 2019-08-08
     */
    public function doDelete()
    {
        $id = input('id', 0, "intval");
        if (!$id) {
            return ['code' => 2000, 'msg' => '非法请求'];
        }
        try {
            Db::name('ad_postion')->where('ad_postion_id', '=', $id)->delete();//删除广告位
            Db::name('ad')->where('ad_postion_id', '=', $id)->delete();//删除该广告位所有广告
            return ['code' => 0, 'msg' => '删除成功！'];
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => '操作失败！'];
        }
    }
}